package cn.itcast.order.config;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.order.mapper.OrderDetailMapper;
import cn.itcast.order.service.OrderDetailService;
import cn.itcast.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class OrderMqListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @org.springframework.amqp.rabbit.annotation.Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = "delay"
    ))
    public void listenDelayedQueue(String msg) {
      try {
          log.info("接收到delay.queue的延迟消息:{}",msg);
          Order order = orderService.getById(msg);
          System.out.println(order);
          if (order.getStatus()==1){
              LambdaQueryWrapper<OrderDetail> wrapper = Wrappers.lambdaQuery();
              wrapper.eq(OrderDetail::getOrderId,msg);
              OrderDetail orderDetail = orderDetailMapper.selectOne(wrapper);
              System.out.println("orderDetail"+orderDetail);
              Item item = itemClient.ByIdQuery(orderDetail.getItemId());
              item.setStock(item.getStock()+orderDetail.getNum());
              itemClient.reviseGood(item);  //修改商品库存
              order.setStatus(5);
              orderService.updateById(order);//修改订单状态为5 超时未支付
              log.debug("修改成功");
          }
      }catch (Exception e){
          log.error(ExceptionUtils.getStackTrace(e));
      }

    }
}



